package modules.march
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import util.pool.IPoolable;
	import util.Tools;
	
	/**
	 * 块单元
	 * @author WLDragon 2013-12-21
	 */
	public class Block extends Sprite implements IPoolable
	{
		
		public function Block()
		{
			init();
		
		}
		
		private function init():void
		{
			mTexture = new Bitmap(new BitmapData(32,32,true,0x000000));
			mBorder = new Sprite;
			
			var w:int = Tools.textures.w;
			var h:int = Tools.textures.h;
			//一块提供鼠标事件的区域
			var s:Sprite = new Sprite;
			s.buttonMode = true;
			with (s.graphics)
			{
				beginFill(0, 0);
				drawRect(0, 0, w, h);
				endFill();
			}
			
			addChild(mTexture);
			addChild(s);
			addChild(mBorder);
			
			s.addEventListener(MouseEvent.CLICK, onClick);
			s.addEventListener(MouseEvent.ROLL_OVER,onOver);
		}
		
		/**
		 * 改变状态
		 * @param	$selected 是否为选中状态
		 */
		public function changeState($selected:Boolean):void
		{
			var w:int = Tools.textures.w - 1;
			var h:int = Tools.textures.h - 1;

			with (mBorder.graphics)
			{
				clear();
				lineStyle(1);
				moveTo(0, h);
				lineTo(w, h);
				lineTo(w, 0);
			}
			
			if ($selected)
			{
				with (mBorder.graphics)
				{
					lineStyle(1,0xFF00FF);
					moveTo(0, 0);
					lineTo(0, h-1);
					lineTo(w-1, h-1);
					lineTo(w-1, 0);
					lineTo(0, 0);
				}
			}
		
		}
		
		private function onOver(e:MouseEvent):void 
		{
			mOverHandler.call(null,this);
		}
		
		private function onClick(e:MouseEvent):void
		{
			mClickHandler.call(null, this);
		}
		
		public function setTexture($index:int):void
		{
			_type = $index;
			mTexture.bitmapData = Tools.textures.getData($index);
		}
		
		public function renew(arg:Object = null):void
		{
			_type = 0;
			changeState(false);
			this.x = arg.x;
			this.y = arg.y;
			arg.parent.addChild(this);
			mClickHandler = arg.click;
			mOverHandler = arg.over;
		}
		
		public function release():void
		{
			parent.removeChild(this);
			mBorder.graphics.clear();
			mTexture.bitmapData = null;
			mClickHandler = null;
		}
		
		/**纹理位图*/
		private var mTexture:Bitmap;
		/**描边*/
		private var mBorder:Sprite;
		/**点击处理函数*/
		private var mClickHandler:Function;
		/**鼠标经过处理函数*/
		private var mOverHandler:Function;
		/**纹理的序号*/
		private var _type:int;
		
		/**纹理的序号*/
		public function get type():int 
		{
			return _type;
		}
	}

}